import React from 'react';
import { Form, Input, Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

const ProductForm = ({ onCancel, product }) => {
    const [form] = Form.useForm();

    // 设置表单初始值
    React.useEffect(() => {
        if (product) {
            form.setFieldsValue({
                name: product.name,
                price: product.price,
                stock: product.stock,
                // 这里需要根据实际情况设置图片字段
            });
        }
    }, [product, form]);

    const onFinish = (values) => {
        console.log('Received values:', values);
        // 在这里处理新增商品的逻辑，可以将数据发送到后端保存等
        onCancel();
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <Form form={form} name="product-form" onFinish={onFinish} onFinishFailed={onFinishFailed}>
            <Form.Item
                name="name"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称!' }]}
            >
                <Input placeholder="请输入商品名称" />
            </Form.Item>
            <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入商品价格!' }]}
            >
                <Input type="number" placeholder="请输入商品价格" />
            </Form.Item>
            <Form.Item
                name="stock"
                label="库存"
                rules={[{ required: true, message: '请输入商品库存!' }]}
            >
                <Input type="number" placeholder="请输入商品库存" />
            </Form.Item>
            <Form.Item
                name="image"
                label="商品图片"
                rules={[{ required: true, message: '请上传商品图片!' }]}
            >
                <Upload name="logo" action="/upload.do" listType="picture">
                    <Button icon={<UploadOutlined />}>点击上传</Button>
                </Upload>
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">
                    提交
                </Button>
                <Button style={{ marginLeft: '10px' }} onClick={onCancel}>
                    取消
                </Button>
            </Form.Item>
        </Form>
    );
};

export default ProductForm;
